import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data';
import { CartItem } from '@/types/cart';
export default defineStore('cart',{
  state() {
      return{
      list:[] as CartItem[]
      }
  },
  actions:{
    async addCart(data: { skuId: string; count: number }) {
      await request.post('/member/cart', data)
      this.getList()
  },
    async getList(){
      const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
      this.list = res.data.result
    },
    async deletCartList( skuId: string[]){
          await request.delete('/member/cart',{data:{id:skuId}})
          this.getList()
    }

},
getters:{
  // 计算有效商品列表 isEffective = true  filter
  effectiveList():CartItem[]{
    return this.list.filter(item=> item.isEffective && item.stock > 0)
  },
   // 有效商品总数量 把effctiveList中的每一项的count叠加起来
   effectiveListCounts():number{
    return this.effectiveList.reduce((sum,item)=>sum += item.count,0)
   },
   // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
   effectiveListPrice():string{
    return this.effectiveList.reduce((sum,item)=>sum += item.count * +item.nowPrice,0).toFixed(2)
   }
}
})